package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 文件的上传和下载
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;
    @Value("${reggie.localPath}")
    private String localPath;

    private final String projectPath = System.getProperty("user.dir");



    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //file是一个临时文件，需要转存到指定目录，否则本次请求完成会删除临时目录
        log.info("上传的文件：{}", file.toString());

        //获得原始目录的文件名
        String originalFilename = file.getOriginalFilename();
        //使用UUID重新生成，防止文件名重复导致覆盖
        String uuid = UUID.randomUUID().toString();

        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = uuid + suffix;

        String basePath1 = projectPath+localPath;


        //判断当前目录是否存在
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        try {
            //将临时文件转存到指定目录
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);

    }


    /**
     * 文件下载
     *
     * @param name     文件名
     * @param response 输出流显示文件
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            FileInputStream inputStream = new FileInputStream(new File(basePath + name));
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");

            IOUtils.copy(inputStream,outputStream);
            IOUtils.closeQuietly(null);

//            int len = 0;
//            byte[] bytes = new byte[1024];
//            while ((len = inputStream.read(bytes)) != -1) {
//                outputStream.write(bytes, 0, len);
//                outputStream.flush();
//            }
//            outputStream.close();
//            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}
